<template>
  <!--课程详细信息页-->
  <div class="max">
    <!--课程详情，图片、价格、讲师-->
    <div class="c_toop">
      <div style="margin-left: 12%;margin-right: 12%" class="c_left">
        <ul class="detail_header">
          <li><a href="/">首页</a><span>&gt;</span></li>
          <li><a href="/Home">录播中心</a><span>&gt;</span></li>
          <li>{{ xiangxixinxi.title }}</li>
        </ul>
      </div>
      <div v-if="!V" style="margin-left: 12%;margin-right: 12%" class="c-toop-mode">
        <!--课程图片-->
        <div class="c-center-left">
          <el-image :src="xiangxixinxi.cover" style="margin-right: 30px;height: 255px"></el-image>
        </div>
        <!--课程详情-->
        <div class="c_center_right">
          <ul>
            <li>
              <div class="d_oneday" style="color:white">
                <div style="color: #909399">
                  <span style="font-size: 20px">{{ xiangxixinxi.title }}</span>
                </div>
                <br>
                <div style="color: #909399">
                  价格 :￥
                  <span class="jiage">{{ xiangxixinxi.price }}</span>
                </div>
                <br>
                <el-divider></el-divider>
                <div style="color: #909399"> 讲师:
                  <span>{{ teacher.name }}</span>
                </div>
                <br>
                <div style="color: #909399"> 购买人数:
                  <span>{{ xiangxixinxi.buyCount }}</span>
                </div>
                <br>
                <el-button type="danger" v-if="guankan==400" @click="piy">立即购买</el-button>
                <el-button type="danger" v-else-if="guankan==200" @click="guanka">观看</el-button>
                <el-button type="danger" v-else-if="guankan==300" @click="login">请登录观看</el-button>
              </div>
            </li>
          </ul>
        </div>
      </div>
      <div v-if="V">
        <d-player id="player" style="width: 1120px;height: 356px;position: relative;left: 12%;right: 12%"
                  ref='player' :options="options"></d-player>
      </div>
    </div>
    <div id="bo" style="margin-right: 12%;margin-left: 12%;height: 60%;">
      <div id="bo_left" style="height: 100%;width: 77%;margin-right: 3%;float: left">
        <!--课程介绍-->
        <div class="c-kc">
          <ul class="c-bottom-rest" style="margin-top: 10px">
            <li><a @click="zhanshi(1)">课程介绍</a></li>
            <li><a @click="zhanshi(2)">录播课程 </a></li>
          </ul>
          <div style="padding-top: 12px;margin-right: -150px">
            <el-link type="primary" @click="shoucang"><i class="el-icon-s-flag"></i>
              收藏&nbsp;&nbsp;{{count}}
            </el-link>

          </div>
        </div>
        <!--课程介绍详情-->
        <div class="c-bottom" style="width: 100%;margin-right: 20px;">
          <div v-if="showI===1" class="c_bottom_bottom">
            <p style="text-align: left;padding-top: 30px"><b>|</b>&nbsp;&nbsp;<b>课程介绍</b></p>
            <div v-if="sss" style="margin: 20px 0 0 50px">
              <div v-html="desc" id="ddd"></div>
            </div>
            <div v-else>

            </div>
          </div>
          <div v-if="showI===2">
            <p style="text-align: left;padding-top: 30px;padding-bottom: 15px">
              <b>|</b>&nbsp;&nbsp;<b>课程大纲</b></p>
            <div v-for="(items,indexs) in videos" :key="indexs" style="text-align: left">
              <span style="margin-left: 17px;color: #999999;display: block;padding-top: 20px"
                    v-if="items.title">{{ items.title }}</span>
              <div v-for="(item,index) in items.haveVideo" :ref="item.id" @click="toPlay(item)"
                   @mouseenter="changeWidth(item.id)" @mouseleave="back(item.id)" :key="index"
                   style="height: 40px;text-align: left;margin-top: 10px">
                <div style="margin-left: 30px ;padding-top: 10px">
                  <el-link :underline="false" style="color: #909399"
                           class="el-icon-video-play"></el-link>&nbsp;
                  <el-link :underline="false" style="color: #909399">{{ item.title }}</el-link>
                  <div style="float: right;color: #909399;padding-right: 20px">
                    <el-link :underline="false" style="color: #909399">{{ item.duration }}m</el-link>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div id="bo_right" style="width: 20%;float: left;height: 100%">
        <div style="margin-top: 40px;height: 40px;background-color:white;">
          <div style="padding-top: 13px"><span>讲师简介</span></div>
        </div>

        <div style="background-color:white;margin-top: 3px;">
          <img :src=teacher.avatar @click="teone(teacher.id)"  style="float: left;width: 50px;height: 50px"><span>{{ teacher.name }}</span>
          <a @click="guanzhu" style="float: right;">关注<i class="el-icon-upload"></i></a>
          <p>{{ teacher.intro }}</p>
        </div>
      </div>
    </div>
    <el-dialog
        title="收银台"
        :visible.sync="zhifu"
        width="600px"
    >
      <table style="width: 100%">
        <tr style="width: 100%">
          <td>课程名称</td>
          <td style="float: right">价格</td>
        </tr>
        <tr>
          <td width="40%"><img :src="xiangxixinxi.cover" width="120px" height="60px"></td>
          <td width="30%">{{ xiangxixinxi.title }}</td>
          <td width="30%">{{ xiangxixinxi.price }}</td>
        </tr>
      </table>

      <div style="width: 100%;padding-bottom: 100px">
        <img src="../assets/微信.png" ref="2" @click="ttt(2)">
        <img src="../assets/支付宝.png" ref="1" @click="ttt(1)">
      </div>
      <div style="width: 100%;">
        <el-button type="danger" @click="zf">下一步</el-button>
      </div>
    </el-dialog>
    <el-dialog
        title="收银台"
        :visible.sync="dialogVisible"
        width="30%"
    >
      <div style="text-align: center">
        <p>支付</p>
        <div style="border: 1px solid #f3f3f3;width: 220px;padding: 10px;margin: 0px auto">
          <vue-qr
              :text="payResult.code_url"
              :margin="0"
              colorDark="green"
              colorLight="#fff"
              :size="200">

          </vue-qr>
        </div>
      </div>
      <el-divider></el-divider>
      <div style="font-size: 13px">
        提示:<br>
        支付成功前请勿手动关闭页面<br>
        二维码两小时内有效,请及时扫码支付<br>
      </div>
    </el-dialog>
    <el-dialog
        title="收银台"
        :visible.sync="dialogVisible"
        width="30%"
    >
      <div style="text-align: center">
        <p>支付</p>
        <div style="border: 1px solid #f3f3f3;width: 220px;padding: 10px;margin: 0px auto">
          <vue-qr
              :text="payResult.code_url"
              :margin="0"
              colorDark="green"
              colorLight="#fff"
              :size="200">
          </vue-qr>
        </div>
      </div>
      <el-divider></el-divider>
      <div style="font-size: 13px">
        提示:<br>
        支付成功前请勿手动关闭页面<br>
        二维码两小时内有效,请及时扫码支付<br>
      </div>
    </el-dialog>
  </div>
</template>


<script>
import vueQr from 'vue-qr'

export default {
  name: "courseDetails",
  data() {
    return {
      options: {
        container: document.getElementById('player'),
        theme: 'pink',  // 风格颜色，例如播放条，音量条的颜色
        loop: false,  // 是否自动循环
        lang: 'zh-cn',  // 语言，'en', 'zh-cn', 'zh-tw'
        screenshot: true,  // 是否允许截图（按钮），点击可以自动将截图下载到本地
        hotkey: true,  // 是否支持热键，调节音量，播放，暂停等
        preload: 'auto',  // 自动预加载
        volume: 0.7,  // 初始化音量
        currentTime: '',
        video: {
          url: ''
        },
      },
      V: false,
      showI: 1,
      sss: true,
      //课程详情
      desc: "",
      aliPayShowPay: false,
      payResult: {
        code_url: "", //二维码的地址
        out_trade_no: "5", //订单号
        total_fee: 0, //支付的金额
        course_id: "", //课程id
        logoSrc: "assets/1.jpg"//微信二维码中间小logo
      },
      timer1: '',
      dialogVisible: false, //弹出框
      //登录者为当前课程创建者
      isMe: false,
      //支付宝或者微信
      radio1: 1,
      //支付状态
      zhifu: false,
      guankan: "200",
      coucseid: "",
      userData: {},
      //课程信息
      xiangxixinxi: {},
      //教师信息
      teacher: {},
      videos: [],
      PlayHistory: {},
      timer2: '',
      timer3: '',
      startTime: 0,
      //收藏人数
      count:"",
    }
  },
  created() {
    this.searchMember();
    const routerParams = this.$route.query.key
    if (routerParams != undefined) {
      this.coucseid = routerParams;
    }
    this.getAllTeacher();
    this.init()
    clearTimeout(this.timer3);  //清除延迟执行
    this.timer3 = setTimeout(() => {   //
      if (this.userData.teacherId == this.teacher.id) {
        this.isMe = true;
      }
      this.guankans();
    }, 1000);
  }
  ,
  methods: {
    teone(item){
      this.$router.push({
        path:'/teacherOne',
        query:{
          id:item
        }
      })
    },
    init(){
      var that = this;
      this.$http.get("/core/Course/findCourseCount?id="+this.coucseid).then(function (resp){
        console.log(resp);
        that.count=resp.data.result
      })
    },
    ttt(item){
      this.radio1=item;
      if(item==1){
        this.$refs[1].className="sss";
        this.$refs[2].className="";
      }else {
        this.$refs[2].className="sss";
        this.$refs[1].className="";
      }
    },
    guanzhu() {
      console.log(this.userData);
      var tid = this.teacher.id;
      var cid = this.userData.id;
      var that = this;
      this.$http.post(`/core/follow/addFollow/` + tid + "/" + cid).then(function (resp) {
        if (resp.data.code == 2000) {
          that.$message({
            type: "success",
            message: resp.data.msg
          })
        } else {
          that.$message({
            type: "error",
            message: resp.data.msg
          })
        }

      })
    },
    changeWidth(id) {
      this.$refs[id][0].style.background = " #dddddd";
    },
    back(id) {
      this.$refs[id][0].style.background = "";
    },
    toPlay(item) {
      var that = this;
      if (item.isFree === true) {
        this.V = true;
        this.options.video.url = item.videoSourceUrl;this.$nextTick(() => {
          this.$refs.player.dp.switchVideo({
            url: item.videoSourceUrl,
          })
        })
      } else if (this.guankan == 200) {
        this.$http.get(`/study/get/${that.userData.id}/${item.chapterId}`).then(function (success) {
          if (success.data.code === 200) {
            that.startTime = success.data.result.playTime;
          }
        })
        this.$nextTick(() => {
          this.$refs.player.dp.switchVideo({
            url: item.videoSourceUrl,
          })
          this.$refs.player.dp.seek(that.startTime);
        })
        this.options.video.url = "";
        var _this = this;
        this.V = true;
        this.options.video.url = item.videoSourceUrl;

        this.timer2 = setInterval(() => {
          this.PlayHistory.userId = this.userData.id;
          this.PlayHistory.vedeoId = item.chapterId;
          this.$nextTick(() => {
            this.PlayHistory.playTime = this.$refs.player.dp.video.currentTime;
            if (this.PlayHistory.playTime > item.duration) {
              clearInterval(_this.timer2)
              _this.timer2 = null;
            }
          })
          this.$http.post(`/core/video/upPlayHistory`, this.PlayHistory).then(function (success) {
          })
        }, 2000);
      } else if (this.guankan === 400) {
        this.$message.info("请购买")
      } else {
        this.$message.info("请登录")
      }
    },
    //查询用户
    searchMember() {
      var that = this;
      var token = sessionStorage.getItem("token");
      if (token == null) {
        that.$message("登录查看内容")
      } else {
        console.log(token);
        this.$http.get(`/member/findMemberByToken/${token}`).then(function (successCallback) {
          if (successCallback.data.code === 2000) {
            that.userData = successCallback.data.result;
          }
        })
      }
    }
    ,
    shoucang() {
      var that = this;
      var da = {
        course: that.xiangxixinxi,
        teacher: that.teacher,
        id: that.coucseid,
        member: that.userData
      }
      this.$http.post("/core/teacherandcou/shoucangCourse", da).then(function (resp) {
        that.$message.warning(resp.data.msg);
        that.init()
      })
    }
    ,
    guanka() {
      this.$message.info("请选择课程进行观看")
    }
    ,
    zhanshi(it) {
      this.showI = it;
      if (it === 2) {
        var _this = this;
        _this.$http.get(`/core/chapter/getVideoInfo/${_this.xiangxixinxi.id}`).then(function (success) {
          console.log(success)
          if (success.data.code === 200) {
            _this.videos = success.data.result;
          }
        })
      }
    }
    ,
    //购买
    piy() {
      this.zhifu = true;
    }
    ,
    //路由到登录
    login() {
      this.$router.push({
        path: '/login',
        query: {
          key: 0
        }
      })
    }
    ,
    //是否可以观看
    guankans() {
      var that = this;
      this.$nextTick(function () {
        if (this.xiangxixinxi.price == 0 || this.isMe === true) {
        } else {
          that.$http.get("/core/teacherandcou/userAndCourse?id=" + that.coucseid).then(function (resp) {
            var data = resp.data;
            if (data.code == 200) {
              that.guankan = 200;
            } else if (data.code == 300) {
              that.guankan = 300;
            } else {
              that.guankan = 400;
            }
          })
        }
      })
    }
    ,
    //初始化
    getAllTeacher() {
      var that = this;
      this.$http.get("/core/teacherandcou/getteacherandcou?id=" + this.coucseid).then(function (resp) {
        that.teacher = resp.data.result.teacher
        that.xiangxixinxi = resp.data.result.course
        that.desc = resp.data.result.courseDescription.description

      })
    }
    ,
    //支付
    zf() {
      var that = this;
      this.zhifu = false;
      //生成订单
      var da = {course: that.xiangxixinxi, teacher: that.teacher, id: that.coucseid}
      this.$http.post("/order/insertOrder", da).then(function (resp) {
        if (resp.data.code == 200) {
          //支付宝
          var da = resp.data.result
          if (that.radio1 == 1) {
            that.aliPayCreateNavite(da.orderNo, da.totalFee, da.courseTitle, "慎重下单");
            that.timer2 = setInterval(() => {
              that.aliPayqueryPayStatus(da.orderNo)
            }, 3000);
          } else {
            that.dialogVisible = true;
            that.payResult.out_trade_no = da.orderNo
            that.wxzf();
            // 设置一个定时任务，每隔3秒调用一次
            that.timer1 = setInterval(() => {
              that.queryPayStatus(that.payResult.out_trade_no)
            }, 3000);
            that.wxzf();
          }
        }
      })

    }
    ,
    //支付宝支付
    aliPayCreateNavite(orderNo, totalFee, countTitle, body) {
      var that = this;
      //支付成功
      this.$http.get("/order/payLog/ali/getStatus", {
        params: {
          "orderNo": orderNo,
          "amount": totalFee,
          "product": countTitle,
          "body": body
        }
      }).then(function (resp) {
        if (resp != null) {
          that.dialogVisible = true
          //把支付宝返回的二维码的路径返回给vue-qr的二维码解析器
          that.payResult.code_url = resp.data.alipay_trade_precreate_response.qr_code;
        } else {
          // 支付失败
          that.payStep = 3;
          that.$message.error("二维码生成失败,请查询订单是否已经支付。");
        }

      })
    }
    ,
    /**
     * 查询支付宝支付的状态
     */
    aliPayqueryPayStatus(orderNo) {
      //订单号为空则停止方法
      if (orderNo == '') {
        return;  //结束当前方法
      }
      var that = this;
      this.$http.get(`/order/payLog/ali/getAliPayStatus/${orderNo}`).then(r => {
        if (r.data.code === 2000) {
          //如果支付成功，清除定时器
          clearInterval(that.timer2)
          that.timer2 = null;
          //支付成功显示支付成功的弹框
          that.payStep = 2
          //关闭微信的弹框
          this.dialogVisible = false;
          that.getAllTeacher();
          that.guankans();
          that.$message({
            type: 'success',
            message: '支付成功!'
          })
          that.dialogVisible = false;
          //跳转到课程详情页面观看视频
          //that.$router.push({path: '/course/' + that.payResult.course_id})
        }
      })
    }
    ,
    wxzf() {
      var that = this;
      that.$http.get("/order/pay/createNatice/" + that.payResult.out_trade_no).then(function (resp) {
        if (resp.data.code === 2000) {
          that.dialogVisible = true
          that.payResult = resp.data.result;
        } else {
          that.$message.error("二维码生成失败,请查询订单是否已经支付。");
        }

      })
    }
    ,
    queryPayStatus(orderNo) {
      var that = this;
      that.$http.get("/order/pay/getPayStatus/" + orderNo).then(r => {
        if (r.data.code === 2000) {
          //如果支付成功，清除定时器
          clearInterval(that.timer1)
          that.timer1 = null;
          that.$message({
            type: 'success',
            message: '支付成功!'
          })
          that.dialogVisible = false;
          that.getAllTeacher();
          that.guankans();
          //跳转到课程详情页面观看视频
          //that.$router.push({path: '/course/' + that.payResult.course_id})
        }
      })
    }
  },
  destroyed: function (to, form, next) {
    clearInterval(this.timer2)
    this.timer2 = null;
  },
  components: {
    vueQr
  }
}
</script>

<style scoped>
.sss{
  border: navajowhite 1px solid;
}
#ddd {
  text-align: left;
}

.max {
  width: 100%;
  height: 100Vh;
}

.c_bottom_bottom {
  width: 100%;
  height: 80%;
  /*background: #dddddd;*/
}

.c-bottom {
  width: 80%;
  height: 70%;
  float: left;
  margin-top: 30px;
  background-color: white;
}


.d_oneday > div {
  margin-top: 20px;
  margin-bottom: 20px;
}

.c_bottom_top > li > a {
  float: left;
  line-height: 57px;
  margin: 0 10px;
  font-size: 14px;
  color: white;
}

.c_left {
  height: 60px;
}

.detail_header > li {
  float: left;
  line-height: 57px;
  margin: 0 10px;
  color: white;
  font-size: 14px;
}

.detail_header > li > a {
  float: left;
  line-height: 57px;
  margin: 0 10px;
  color: white;
  font-size: 14px;
}

.c-bottom-rest {
  margin-left: 20px;
  float: left;
}

/*课程详情目录*/
.c-kc {
  width: 100%;
  height: 40px;
  background-color: white;
  margin-top: 40px;
  float: left;
}

ul {
  list-style: none;
}

/*课程图片*/
.c-center-left {
  width: 50%;
  height: 400px;
  float: left;
}

.c_center_right {
  width: 50%;
  float: left;
}

.c-bottom-rest > li {
  float: left;
  margin-right: 40px;
}

.c_toop {
  width: 100%;
  height: 480px;
  background-color: #000000;
  /*文字位置*/
  text-align: left;
  font-family: 微软雅黑, "\5b8b\4f53";
}

.jiage {
  color: red;
  font-size: 20px;
}
</style>